package com.lottery.ruok.lottrey.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.lib.dialog.BottomDialog;
import com.android.lib.dialog.Builder;
import com.applozic.mobicomkit.uiwidgets.conversation.messageUtils.ChatRecordUtils;
import com.applozic.mobicomkit.uiwidgets.conversation.messageUtils.SearchRecordUtils;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.SearchChannelAdapter;
import com.lottery.ruok.lottrey.adapter.recyclleradapter.RecyclerItemClickListener;
import com.lottery.ruok.lottrey.chat.RongCloudChatActivityHelper;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.AddChatAdminResquest;
import com.lottery.ruok.lottrey.retrofitModule.request.ResumeChatUserRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.SearchChannelUser;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRoomUsersResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.OperationSuccessResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import utils.Utils;
/*
* 群成员管理
* */

public class SearchChannelActivity extends BaseActivity {
    public static final int WHAT_HTTP_SEARCH = 1;
    public final long HTTP_TIME = 500;

    public long lastEditTime;
    public boolean isChecking;//是否在校验中
    @BindView(R.id.et_text)
    EditText etText;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.view_recycler)
    RecyclerView viewRecycler;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_HTTP_SEARCH:
                    if (System.currentTimeMillis() - lastEditTime > HTTP_TIME) {
                        //可以请求
                        httpSearch(etText.getText().toString().trim());
                        isChecking = false;
                    } else {
                        isChecking = true;
                        sendEmptyMessageDelayed(WHAT_HTTP_SEARCH, HTTP_TIME);
                    }
                    break;
            }
        }
    };
    private LinearLayoutManager linearLayoutManager;
    private SearchChannelAdapter searchChannelAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_channel);
        ButterKnife.bind(this);
        init();
        initView();
        load();
    }

    private void load() {

    }

    private void initView() {

        searchChannelAdapter = new SearchChannelAdapter(this);
        linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        viewRecycler.setLayoutManager(linearLayoutManager);
        viewRecycler.setAdapter(searchChannelAdapter);
        viewRecycler.addOnItemTouchListener(new RecyclerItemClickListener(SearchChannelActivity.this) {
            @Override
            protected boolean onItemClick(View view, final int position) {
                final GetRoomUsersResponse.ListBean listBean = searchChannelAdapter.getList().get(position);
                if (!UserInfo.getUsername().equals(listBean.getUsername())) {
                    Builder builder = new Builder(SearchChannelActivity.this);//首先自己不能和自己聊天，已经是管理员的人不能再被设为管理员，自己也不能移除自己
                    builder.addOption("私聊", Color.parseColor("#007aff"), new BottomDialog.OnOptionClickListener() {
                        @Override
                        public void onOptionClick() {
                            RongCloudChatActivityHelper.startPrivateChat(SearchChannelActivity.this, listBean.getRy_id(), listBean.getNickname());
                        }
                    });
                    if (listBean.getChatroom_role() != null && listBean.getChatroom_role().equals("1")) {
                        builder.addOption("选定为管理员", Color.parseColor("#007aff"), new BottomDialog.OnOptionClickListener() {
                            @Override
                            public void onOptionClick() {
                                //sendAnalyticMsg("lottery_" + MobiComConversationFragment.ANALYTIC_VERSION + "_chat_group_set_admin");

                                Utils.createDialog(SearchChannelActivity.this, "确定选定用户" + listBean.getNickname() + "为管理员",
                                        "取消", "确定",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {

                                            }
                                        }, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                RetrofitBase.getRetrofit().create(AddChatAdminResquest.class)
                                                        .getResult(UserInfo.getToken(), listBean.getUsername(), 1)
                                                        .compose(RxHelper.<OperationSuccessResponse>handleResult())
                                                        .subscribe(new RxSubscribe<OperationSuccessResponse>(SearchChannelActivity.this) {
                                                            @Override
                                                            protected void _onNext(OperationSuccessResponse operationSuccessResponse) {
                                                                Utils.showToast(operationSuccessResponse.getMsg());

                                                                listBean.setChatroom_role("3");
                                                                searchChannelAdapter.notifyDataSetChanged();
                                                            }

                                                            @Override
                                                            protected boolean showDialog() {
                                                                return true;
                                                            }
                                                        });
                                            }
                                        });
                            }
                        });
                    }
                    //如果是超级管理员，无法被移除
                    if (listBean.getChatroom_role() != null && !listBean.getChatroom_role().equals("3")) {
                        builder.addOption("移除此成员", Color.parseColor("#007aff"), new BottomDialog.OnOptionClickListener() {
                            @Override
                            public void onOptionClick() {
                                //sendAnalyticMsg("lottery_" + MobiComConversationFragment.ANALYTIC_VERSION + "_chat_group_remove_member");
                                Utils.createDialog(SearchChannelActivity.this, "确定把用户" + listBean.getNickname() + "从群里移除",
                                        "取消", "确定",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {

                                            }
                                        }, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                RetrofitBase.getRetrofit().create(ResumeChatUserRequest.class)
                                                        .getResult(UserInfo.getToken(), listBean.getRy_id(), 0)
                                                        .compose(RxHelper.<OperationSuccessResponse>handleResult())
                                                        .subscribe(new RxSubscribe<OperationSuccessResponse>(SearchChannelActivity.this) {
                                                            @Override
                                                            protected void _onNext(OperationSuccessResponse operationSuccessResponse) {
                                                                Utils.showToast(operationSuccessResponse.getMsg());

                                                                searchChannelAdapter.getList().remove(position);
                                                                searchChannelAdapter.notifyDataSetChanged();
                                                            }

                                                            @Override
                                                            protected boolean showDialog() {
                                                                return true;
                                                            }
                                                        });
                                            }
                                        });
                            }
                        });
                    }


                    if (listBean != null && listBean.getDataType() != 0) {
                        builder.addOption("删除该记录", Color.parseColor("#ff0000"), new BottomDialog.OnOptionClickListener() {
                            @Override
                            public void onOptionClick() {
                                //sendAnalyticMsg("lottery_" + MobiComConversationFragment.ANALYTIC_VERSION + "_chat_group_remove_member");
                                Utils.createDialog(SearchChannelActivity.this, "确定把用户" + listBean.getNickname() + "的记录移除",
                                        "取消", "确定",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {

                                            }
                                        }, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                if (listBean.getDataType() == 1) {
                                                    //删除聊天记录
                                                    ChatRecordUtils.delete(listBean.getUsername());
                                                } else if (listBean.getDataType() == 2) {
                                                    //删除搜索记录
                                                    SearchRecordUtils.delete(listBean.getUsername());
                                                    searchChannelAdapter.remove(listBean);
                                                }
                                            }
                                        });
                            }
                        });
                    }

                    builder.create().show();
                } else {
                    Utils.showToast("这是你本人噢");
                }
                return true;
            }
        });
        etText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                lastEditTime = System.currentTimeMillis();
                if (Utils.isEmpty(etText.getText().toString().trim())) {
                    //设置历史数据
                    searchChannelAdapter.setList(SearchRecordUtils.getSearchHistoryList());
                } else {
                    autoHttpSearch();
                }
            }
        });
        //设置历史数据
        searchChannelAdapter.setList(SearchRecordUtils.getSearchHistoryList());
    }

    /**
     * 请求网络
     *
     * @return
     */
    private void autoHttpSearch() {
        if (!isChecking) {
            isChecking = true;
            handler.sendEmptyMessageDelayed(WHAT_HTTP_SEARCH, HTTP_TIME);
        }
    }

    /**
     * 搜索
     */
    private void httpSearch(String key) {
        RetrofitBase.getRetrofit().create(SearchChannelUser.class)
                .getResult(UserInfo.getToken(),
                        UserInfo.getRoomId(),
                        0, 100, key)
                .compose(RxHelper.<GetRoomUsersResponse>handleResult())
                .subscribe(new RxSubscribe<GetRoomUsersResponse>(SearchChannelActivity.this) {
                    @Override
                    protected void _onNext(GetRoomUsersResponse operationSuccessResponse) {
                        if (operationSuccessResponse != null) {
                            List<GetRoomUsersResponse.ListBean> list = operationSuccessResponse.getList();
                            if (list != null) {
                                searchChannelAdapter.setList(list);
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    private void init() {

    }

    public static void startActivity(Activity activity) {
        Intent intent = new Intent(activity, SearchChannelActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        if (handler.hasMessages(WHAT_HTTP_SEARCH)) {
            handler.removeMessages(WHAT_HTTP_SEARCH);
        }
        super.onDestroy();
    }

    @OnClick(R.id.tv_cancel)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                if (!Utils.isEmpty(etText.getText().toString())) {
                    etText.setText("");
                    return;
                }
                finish();
                break;
        }
    }
}
